package com.wl.dzt.filter;

import com.wl.dzt.basic.user.User;
import com.wl.dzt.sys.constant.CommConstant;
import com.wl.dzt.sys.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 登录过滤器, 过滤所有前缀为admin请求
 */
@Configuration
@Order(10)
@WebFilter(filterName = "loginFilter", urlPatterns = {"/admin/*"})
public class LoginFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User user = WebUtils.getUser(request);
        String[] split = request.getRequestURI().split("/");
        if (split.length > 0) {
            if (user == null && (!split[split.length - 1].equals("index.html") || split[split.length - 1].equals("index_debug.html"))) {
                WebUtils.print(CommConstant.NO_SESSION, response);
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
